package com.songhuan.web.tools;

import com.baidu.aip.face.AipFace;
import com.songhuan.web.tools.exception.CustomException;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 阿里云 人脸识别工具类
 */
public class FaceUtils {

//    public String APP_ID = "71707176";
//public String API_KEY = "w3CKEXr4EYxvYII1oxU06cZO";
//public String SECRET_KEY = "DNRuump1VzywnQFK21qgU2Z7fyRNywxC";
//public String GROUD_LIST = "Users";

    public static final String APP_ID = "71707176";
    public static final String API_KEY = "w3CKEXr4EYxvYII1oxU06cZO";
    public static final String SECRET_KEY = "DNRuump1VzywnQFK21qgU2Z7fyRNywxC";


    /**
     * 添加用户组
     *  api地址 https://ai.baidu.com/ai-doc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E6%90%9C%E7%B4%A2-mn-%E8%AF%86%E5%88%AB
     */
    public static String GroupAdd(String groupName) {
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        JSONObject jsonObject = client.groupAdd(groupName, options);
        System.out.println("GroupAdd:" + jsonObject.toString(2));
        String errorMsg = jsonObject.getString("error_msg");

        if ("SUCCESS".equals(errorMsg) == false) {
            throw new CustomException("该用户组已经存在");
        }
        return groupName;
    }

    /**
     * 删除用户组
     *  api地址 https://ai.baidu.com/ai-doc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E6%90%9C%E7%B4%A2-mn-%E8%AF%86%E5%88%AB
     */
    public static Boolean GroupDelete(String groupName) {
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        JSONObject jsonObject = client.groupDelete(groupName, options);
        System.out.println("groupDelete:" + jsonObject.toString(2));
        String errorMsg = jsonObject.getString("error_msg");
        return "SUCCESS".equals(errorMsg);

    }


    /**
     * 添加用户人脸
     *  api地址 https://ai.baidu.com/ai-doc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E6%90%9C%E7%B4%A2-mn-%E8%AF%86%E5%88%AB
     */
    public static String FaceAdd(String image,String groupId,String userId)
    {
        //先判断是否存在组
        IfNotExistGroupCreate(groupId);
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        //	图片质量控制 NONE: 不进行控制 LOW:较低的质量要求 NORMAL: 一般的质量要求 HIGH: 较高的质量要求 默认 NONE
        options.put("quality_control", "NONE");
        // 活体检测控制 NONE: 不进行控制 LOW:较低的活体要求(高通过率 低攻击拒绝率) NORMAL: 一般的活体要求(平衡的攻击拒绝率, 通过率) HIGH: 较高的活体要求(高攻击拒绝率 低通过率) 默认NONE
        options.put("liveness_control", "NONE");

        //操作方式 APPEND: 当user_id在库中已经存在时，对此user_id重复注册时，新注册的图片默认会追加到该user_id下,REPLACE : 当对此user_id重复注册时,则会用新图替换库中该user_id下所有图片,默认使用APPEND
        options.put("action_type", "APPEND");


        // 人脸注册
        JSONObject jsonObject = client.addUser(image.replace("data:image/png;base64,",""), "BASE64", groupId, userId, options);
        System.out.println(jsonObject.toString(2));
        String errorMsg = jsonObject.getString("error_msg");
        Integer errorCode = jsonObject.getInt("error_code");

        if(errorCode==222203)
        {
            throw  new CustomException("人脸不完整,请重新上传人脸");
        }
        if(errorCode==222202)
        {
            throw  new CustomException("没有识别到人脸");
        }
        if(errorMsg.equals("SUCCESS")==false)
        {
            throw  new CustomException("异常错误"+errorMsg+"错误编码:"+errorCode);
        }

        String faceToken = jsonObject.getJSONObject("result").getString("face_token");

        return faceToken;
    }

    /**
     * 人脸M：N搜索
     * api地址 https://ai.baidu.com/ai-doc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E6%90%9C%E7%B4%A2-mn-%E8%AF%86%E5%88%AB
     */
    public static String FaceSearch(String image ,String groupId){
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        HashMap<String, Object> options = new HashMap<String, Object>();
        options.put("max_face_num", "10");
        options.put("match_threshold", "70");
        options.put("quality_control", "NONE");
        options.put("liveness_control", "NONE");
        options.put("max_user_num", "20");
        // 人脸搜索 M:N 识别
        JSONObject res = client.multiSearch(image.replace("data:image/png;base64,",""), "BASE64", groupId, options);
        System.out.println(res.toString(2));
        return res.toString(2);
    }

    /**
     * 查询用户的人脸数量
     * api地址 https://ai.baidu.com/ai-doc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E6%90%9C%E7%B4%A2-mn-%E8%AF%86%E5%88%AB
     */
    public static  ArrayList<String> UserFace(String userId,String groupId){
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        // 获取用户人脸列表
        JSONObject jsonObject = client.faceGetlist(userId,groupId, options);
        System.out.println(jsonObject.toString(2));

        ArrayList<String> facesToken = new ArrayList<>();
        if(jsonObject.getString("error_msg").equals("SUCCESS")) {
            JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("face_list");

            for (int i = 0; i < jsonArray.length(); i++) {
                String faceToken = jsonArray.getJSONObject(i).getString("face_token");
                facesToken.add(faceToken);
            }
        }
        return facesToken;
    }
    /**
     * 删除某用户的人脸
     * api地址 https://ai.baidu.com/ai-doc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E6%90%9C%E7%B4%A2-mn-%E8%AF%86%E5%88%AB
     */
    public static String UserFaceDel(String userId,String groupId){

        ArrayList<String> faceTokens = UserFace(userId, groupId);

        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();

        JSONObject jsonObject = client.deleteUser(groupId, userId, options);
        System.out.println(jsonObject.toString(2));
        return jsonObject.toString(2);
    }
    /**
     * 删除某用户的人脸
     * api地址 https://ai.baidu.com/ai-doc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E6%90%9C%E7%B4%A2-mn-%E8%AF%86%E5%88%AB
     */
    public static String UserFaceTokenDel(String userId,String groupId,String faceToken){


        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();

        JSONObject jsonObject = client.faceDelete(userId,groupId,faceToken , options);
        System.out.println(jsonObject.toString(2));
        return jsonObject.toString(2);
    }
    /**
     *如果不存在人脸分组则进行创建一个
     */
    public static void  IfNotExistGroupCreate(String groupName)
    {
        List<Object> groups = GroupList();
        //不存在该组则进行创建
        if(groups.stream().filter(x->x.equals(groupName)).count()==0)
        {
            FaceUtils.GroupAdd(groupName);
        }
    }
    /**
     *查询所有的组
     */
    public  static List<Object> GroupList()
    {
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("start", "0");
        options.put("length", "50");

        // 组列表查询
        JSONObject jsonObject = client.getGroupList(options);

        JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("group_id_list");

        System.out.println(jsonObject.toString(2));
        return   jsonArray.toList();
    }


}
